/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, rule } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = 'docs/no-non-boolean-condition.md';
const DESCRIPTION = 'Conditions in if, while, or do-while statements should be boolean. Using non-boolean values can lead to unexpected behavior due to implicit type conversion.';

function isBooleanType(node: ts.Expression): boolean {
    // 如果节点本身是布尔字面量
    if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) return true;
    
    // 如果节点是二元表达式或者逻辑表达式，可尝试判断类型为布尔
    if (ts.isBinaryExpression(node) || ts.isPrefixUnaryExpression(node)) {
        // 这里简单返回 true，实际可以结合 type checker 扩展
        return true;
    }

    // 其它情况认为不是布尔类型
    return false;
}

export default rule()
  .match((node): node is ts.IfStatement | ts.WhileStatement | ts.DoStatement => ts.isIfStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node))
  .when(node => !isBooleanType(node.expression))
  .report({
      severity: SEVERITY,
      description: DESCRIPTION,
      docPath: DOC_PATH,
  });
